package com.br.aiops.listeners;

import com.br.aiops.counter.AlertLogCounter;
import com.br.aiops.counter.Counter;
import com.br.aiops.events.CountEvent;
import com.br.aiops.schedule.AbstractSchedule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
public class DurationOrTimesListener extends AbstractListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(DurationOrTimesListener.class);

    @Autowired
    private Counter counter;

    @EventListener(condition = "#event.getAlertLogCounter().getRule().getJudgeType() == 4")
    public void handlerEvent(CountEvent event) {
        LOGGER.debug("收到事件: {}", event);
        AlertLogCounter alertLogCounter = event.getAlertLogCounter();

        //统计周期（用于duration或次数恢复）
        AbstractSchedule schedule = getSchedule(alertLogCounter.getRule().getDuration());
        schedule.count(alertLogCounter);

        //阶梯只统计不告警
        if (alertLogCounter.shouldLadderAlert()) {
            return;
        }

        try {
            //保证原子性
            lock.lock();
            //判断周期内没有发送过
            if (!schedule.isFlag(alertLogCounter)) {
                //近duration时间内有告警
                if (schedule.getCount(alertLogCounter) > 0) {
                    //发送告警
                    alertSender.sendAlertMessage(alertLogCounter);
                    schedule.flag(alertLogCounter);
                }
            }

            //判断告警次数
            if (alertLogCounter.getAlertTimes().get() >= alertLogCounter.getRule().getTimes()) {
                //发送告警
                alertSender.sendAlertMessage(alertLogCounter);
                //告警次数清零
                counter.getCounter().get(alertLogCounter.counterKey()).getAlertTimes().set(0);
            }
        } finally {
            lock.unlock();
        }
    }
}
